<?php
if (!defined('__COLA_DIR__')) exit;

/**
 * 安全选项组件
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Widget_Security extends Cola
{
    /**
     * @var string
     */
    private $_token;

    /**
     * @var Widget_Options
     */
    private $_options;

    /**
     * @var boolean
     */
    private $_enabled = true;

    /**
     * 初始化函数
     *
     */
    public function execute()
    {
        $this->_options = $this->widget('Widget_Options');
        $user = $this->widget('Widget_User');

        $this->_token = $this->_options->secret;
        if ($user->hasLogin()) {
            $this->_token .= '&' . $user->salt . '&' . $user->uid;
        }
    }

    /**
     * @param $enabled
     */
    public function enable($enabled = true)
    {
        $this->_enabled = $enabled;
    }

    /**
     * 获取token
     *
     * @param string $suffix 后缀
     * @return string
     */
    public function getToken($suffix)
    {
        return md5($this->_token . '&' . $suffix);
    }

    /**
     * 生成带token的路径
     *
     * @param $path
     * @return string
     */
    public function getTokenUrl($path)
    {
        $parts = parse_url($path);
        $params = array();

        if (!empty($parts['query'])) {
            parse_str($parts['query'], $params);
        }

        $params['_'] = $this->getToken($this->request->getRequestUrl());
        $parts['query'] = http_build_query($params);

        return Common::buildUrl($parts);
    }

    /**
     * 保护提交数据
     *
     */
    public function protect()
    {
        if ($this->_enabled && $this->request->get('_') != $this->getToken($this->request->getReferer())) {
			
            /** 提示信息 */
			$this->result->set(-1, _t("请求无效"));
        }
    }

    /**
     * 获取/输出后台安全路径
     *
     * @param $path
     */
    public function ucenterUrl($path, $echo = true)
    {
		
		$url = $this->getTokenUrl($this->_options->ucenterUrl($path, false));

		if($echo){
			echo $url;
		}else{
			return $url;
		}
    }

    /**
     * 输出安全的action路由路径
     *
     * @param $path
     */
    public function actionUrl($path, $echo = true)
    {

		$url = $this->getTokenUrl($this->_options->actionUrl($path, false));
		
		if($echo){
			echo $url;
		}else{
			return $url;
		}
    }
	
}
 
